import Vue from "vue";
import VueRouter from "vue-router";

//导入 (路由) 组件
import Home from "../views/Home.vue";
import Main from "../views/Main.vue";

import DrugInfo from "@/views/druginfo/drugInfo.vue";
import SupplierInfo from "@/views/druginfo/supplierInfo.vue";

import WarehouseInfo from "@/views/warehouse/warehouseInfo.vue";
import DrugProblemInfo from "@/views/warehouse/drugProblemInfo";
import WarehouseRetInfo from "@/views/warehouse/warehouseRetInfo";
import WhPrchsInfo from "@/views/warehouse/whprchsInfo";

import OrderInfo from "@/views/order/orderInfo.vue";
import UserRetInfo from "@/views/order/userRetInfo";

import Login from "../views/login";
import Register from "../views/adminInfo/register";
import Cookie from "js-cookie";

// 2. 定义路由
const routes = [
  //主路由
  {
    path: "/",
    component: Main,
    name: "home",
    redirect: "/home", //重定向
    //子路由
    children: [
      { path: "home", component: Home }, //首页
      { path: "drugInfo", component: DrugInfo }, //药品信息
      { path: "supplierInfo", component: SupplierInfo }, //供应商信息
      { path: "warehouseInfo", component: WarehouseInfo }, //仓库信息
      { path: "drugProblemInfo", component: DrugProblemInfo }, //药品问题信息
      { path: "warehouseRetInfo", component: WarehouseRetInfo }, //回厂信息
      { path: "whPrchsInfo", component: WhPrchsInfo }, //进货信息
      { path: "orderInfo", component: OrderInfo }, //订单信息
      { path: "userRetInfo", component: UserRetInfo }, //用户退货信息
    ],
  },
  {
    path: "/login",
    name: "login",
    component: Login,
  },
  {
    path: "/register",
    name: "register",
    component: Register,
  },
];

//3.创建router实例
const router = new VueRouter({
  mode: "history",
  // base: "/admin/", //nginx访问接口
  routes, // (缩写) 相当于 routes: routes
});

//4.将router暴露
export default router;

//全局前置导航守卫;
router.beforeEach((to, from, next) => {
  // ...
  // 返回 false 以取消导航
  const token = Cookie.get("token");
  if (to.name === "register") {
    //放行注册访问
    next();
  } else if (!token && to.name !== "login") {
    next({ name: "login" });
  } else if (token && to.name === "login") {
    next({ name: "home" });
  } else {
    next();
  }
});

Vue.use(VueRouter);
